package edu.jmu.dustbinMonitoringSystem.dto;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Wen
 */
public class BaseResultFactory<T extends AbstractBaseDomain> {
    private static final String LOGGER_LEVEL_DEBUG="DEBUG";

    private static BaseResultFactory baseResultFactory;
    private static HttpServletResponse response;
    private static HttpServletRequest request;

    private BaseResultFactory(){

    }

    public static BaseResultFactory getInstance(HttpServletResponse response,HttpServletRequest request){
        if (baseResultFactory==null){
            synchronized (BaseResultFactory.class){
                if (baseResultFactory==null){
                    baseResultFactory=new BaseResultFactory();
                }
            }
        }
        BaseResultFactory.response=response;
        BaseResultFactory.request=request;
        baseResultFactory.initResponse();
        return baseResultFactory;
    }
    /**
     * 构建单笔数据结果
     * @return
     */
    public AbstractBaseResult build(T attributes){
        return new SuccessResult(request.getRequestURI(),attributes);
    }

    /**
     * 构建多笔数据结果
     * @param next
     * @param last
     * @return
     */
    public AbstractBaseResult build(int next, int last, List<T> attributes){
        return new SuccessResult(request.getRequestURI(),next,last,attributes);
    }

    /**
     * 构建请求错误的结果
     * @param code
     * @param title
     * @param detail
     * @param level
     * @return
     */
    public AbstractBaseResult build(int code, String title, String detail, String level){
        response.setStatus(code);
        if (LOGGER_LEVEL_DEBUG.equals(level)){
            return new ErrorResult(code,title,detail);
        }else {
            return new ErrorResult(code,title,null);
        }

    }

    private void initResponse(){
        response.setHeader("Content-Type", "application/vnd.api+json");
    }
}
